package com.example.administrator.yanfoxconn.activity;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TableRow;
import android.widget.TextView;

import com.example.administrator.yanfoxconn.R;
import com.example.administrator.yanfoxconn.adapter.DNReformAdapter;
import com.example.administrator.yanfoxconn.bean.KOInfo;
import com.example.administrator.yanfoxconn.bean.LRMessage;
import com.example.administrator.yanfoxconn.constant.Constants;
import com.example.administrator.yanfoxconn.constant.FoxContext;
import com.example.administrator.yanfoxconn.constant.ImageCaptureManager;
import com.example.administrator.yanfoxconn.utils.BaseActivity;
import com.example.administrator.yanfoxconn.utils.FileUtil;
import com.example.administrator.yanfoxconn.utils.HttpConnectionUtil;
import com.example.administrator.yanfoxconn.utils.HttpUtils;
import com.example.administrator.yanfoxconn.utils.ImageZipUtils;
import com.example.administrator.yanfoxconn.utils.ToastUtils;
import com.example.administrator.yanfoxconn.widget.MyListView;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by Song
 * on 2022/03/10
 * Description：車輛排配 棧板號列表
 */
public class LRPalletListActivity extends BaseActivity implements View.OnClickListener {
    private final int MESSAGE_SET_LIST = 1;//掃描更新
    private final int MESSAGE_TOAST = 2;//掃描失敗彈出框
    private final int MESSAGE_ALERT = 4;//掃描失敗彈出框
    private final int MESSAGE_SET_STOP = 3;//結束
    private final int MESSAGE_SET_UP_LIST = 6;//棧板更新
    private final int MESSAGE_NETMISTAKE = 5;//網絡錯誤


    @BindView(R.id.btn_title_left)
    Button btnBack;//返回
    @BindView(R.id.tv_title)
    TextView tvTitle;//標題

    @BindView(R.id.tr_mt)
    TableRow trMt;
    @BindView(R.id.tr_car)
    TableRow trCar;
    @BindView(R.id.tr_pll)
    TableRow trPll;

    @BindView(R.id.et_pll)
    EditText etPll;
    @BindView(R.id.btn_one)
    Button btnScan;//繼續掃描/結束卸貨
    @BindView(R.id.btn_two)
    Button btnOver;//結束裝貨
    @BindView(R.id.btn_three)
    Button btnUpdate;//棧板更新
    @BindView(R.id.lv_normal)
    MyListView lvNormal;
    @BindView(R.id.ll_lr)
    LinearLayout llLR;
    @BindView(R.id.ll_qrp)
    LinearLayout llQRP;

    private DNReformAdapter dnReformAdapter;
    private List<LRMessage> lrInfoList,scanInfo;
    private LRMessage addMessage=new LRMessage();

    private String flag,pId,qrResult,pNum,build;//flag:SH收貨,FH發貨

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_lr_lv);
        ButterKnife.bind(this);

        qrResult=getIntent().getStringExtra("result");
        pId = getIntent().getStringExtra("pId");
        pNum=getIntent().getStringExtra("pNum");
        flag=getIntent().getStringExtra("flag");
        if (flag.equals("FH")){

            tvTitle.setText("棧板明細");
            btnScan.setText("繼續掃描");
            btnOver.setText("結束裝貨");
            btnUpdate.setText("棧板更新");
            btnOver.setVisibility(View.VISIBLE);
            btnUpdate.setVisibility(View.VISIBLE);

            llLR.setVisibility(View.GONE);
            llQRP.setVisibility(View.VISIBLE);
        }else{
            tvTitle.setText("卸貨完成");
            btnScan.setText("結束卸貨");
            trPll.setVisibility(View.VISIBLE);
            lvNormal.setVisibility(View.GONE);
            llLR.setVisibility(View.GONE);
            llQRP.setVisibility(View.GONE);
                    build=getIntent().getStringExtra("build");
        }

        trCar.setVisibility(View.GONE);
        trMt.setVisibility(View.GONE);
        btnBack.setOnClickListener(this);
        btnScan.setOnClickListener(this);
        btnOver.setOnClickListener(this);
        btnUpdate.setOnClickListener(this);

    }

    /**
     * 用於解決scrollview嵌套listview導致只顯示一條數據的問題
     *
     * @param listView
     */
    public void setListViewHeightBasedOnChildren(ListView listView) {
        // 获取ListView对应的Adapter
        DNReformAdapter listAdapter = (DNReformAdapter) listView.getAdapter();
        if (listAdapter == null) {
            return;
        }
        int totalHeight = 0;
        for (int i = 0, len = listAdapter.getCount(); i < len; i++) {
            // listAdapter.getCount()返回数据项的数目
            View listItem = listAdapter.getView(i, null, listView);
            // 计算子项View 的宽高
            listItem.measure(0, 0);
            // 统计所有子项的总高度
            totalHeight += listItem.getMeasuredHeight();
        }
        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight + (listView.getDividerHeight() *
                (listAdapter.getCount() - 1));
        // listView.getDividerHeight()获取子项间分隔符占用的高度
        // params.height最后得到整个ListView完整显示需要的高度
        listView.setLayoutParams(params);
    }



    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_title_left://返回
                finish();
                break;
            case R.id.btn_one://繼續掃描
                if (flag.equals("FH")){
                    if(Integer.parseInt(FoxContext.getInstance().getPALLETNUM())==lrInfoList.size()){
                        ToastUtils.showShort(LRPalletListActivity.this,"棧板數量已滿！\n應裝棧板："+FoxContext.getInstance().getPALLETNUM()+"\n已裝棧板："+lrInfoList.size());
                    }else{
                Intent intent=new Intent(LRPalletListActivity.this, QrCodeActivity.class);
                intent.putExtra("flag",flag);
                intent.putExtra("num","LR");
                intent.putExtra("no",pId);
                startActivity(intent);
                finish();}
                }else{

                    aboutAlert("結束卸貨",MESSAGE_ALERT);
                }
                break;
            case R.id.btn_two://結束裝貨
                if(Integer.parseInt(FoxContext.getInstance().getPALLETNUM())!=lrInfoList.size()){
                    ToastUtils.showShort(LRPalletListActivity.this,"棧板數量不相符！\n應裝棧板："+FoxContext.getInstance().getPALLETNUM()+"\n已裝棧板："+lrInfoList.size());
                }else{
                aboutAlert("結束裝貨\n應裝棧板："+FoxContext.getInstance().getPALLETNUM()+"\n已裝棧板："+lrInfoList.size(),MESSAGE_SET_STOP);}
                break;
            case R.id.btn_three://棧板更新
                palletListUp(pId);
                break;
        }
    }
    //提交改善
    private void planOver() {
        showDialog();
        final String url = Constants.HTTP_LR_PLANOVER; //此處寫上自己的URL

        JsonObject object = new JsonObject();

        object.addProperty("pId",pId);
        object.addProperty("creator",FoxContext.getInstance().getName());
        object.addProperty("building", build);
        object.addProperty("palletNum",etPll.getText().toString());


        Log.e("----object----",  object.toString());

        //開啟一個新執行緒，向伺服器上傳資料
        new Thread() {
            public void run() {
                //把网络访问的代码放在这里
                try {
                    Log.e("-----url----",  url);
                    String result = HttpConnectionUtil.doPostJsonObject(url, object);
                    if (result != null) {
                        dismissDialog();
                        Log.e("----result-----",  result);
                        JsonObject jsonObject = new JsonParser().parse(result).getAsJsonObject();
                        String errCode = jsonObject.get("errCode").getAsString();
                        if (errCode.equals("200")) {
                            Message message = new Message();
                            message.what = Constants.MESSAGE_ALERT;
                            message.obj = jsonObject.get("errMessage").getAsString();
                            mHandler.sendMessage(message);

                        } else{
                            Message message = new Message();
                            message.what = Constants.MESSAGE_ALERT;
                            message.obj = jsonObject.get("errMessage").getAsString();
                            mHandler.sendMessage(message);
                        }
                    }else{
                        Message message = new Message();
                        message.what = Constants.MESSAGE_NETMISTAKE;
                        mHandler.sendMessage(message);
                        finish();
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }



    private String url2 = "";
    //繼續掃描
    private void upScan(String pId,String palletNo){
        try {

            String palletNo1 =  URLEncoder.encode(URLEncoder.encode(palletNo, "UTF-8"), "UTF-8");

            url2=Constants.HTTP_LR_SCANPALLET + "?pId="+pId+"&palletNo="+palletNo1;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        Log.e("---------", "url2==fff===" + url2);
        showDialog();
        new Thread() {
            @Override
            public void run() {
                //把网络访问的代码放在这里
                String result = HttpUtils.queryStringForPost(url2);
                dismissDialog();
                Gson gson = new Gson();
                if (result != null) {
                    Log.e("---------", "result==fff===" + result);
                    JsonObject jsonObject = new JsonParser().parse(result).getAsJsonObject();
                    String errCode = jsonObject.get("errCode").getAsString();
                    if (errCode.equals("200")) {
                        JsonArray array = jsonObject.get("data").getAsJsonArray();
                        scanInfo = new ArrayList<LRMessage>();

                        for (JsonElement type : array) {
                            LRMessage humi = gson.fromJson(type, LRMessage.class);
                            scanInfo.add(humi);
                        }
                        Message message = new Message();
                        message.what = MESSAGE_SET_LIST;
                        message.obj = jsonObject.get("errMessage").getAsString();
                        mHandler.sendMessage(message);

                    } else {
                        Log.e("-----------", "result==" + result);
                        Message message = new Message();
                        message.what = MESSAGE_TOAST;
                        message.obj = jsonObject.get("errMessage").getAsString();
                        mHandler.sendMessage(message);
                    }
                } else {
                    Message message = new Message();
                    message.what = MESSAGE_NETMISTAKE;
                    mHandler.sendMessage(message);
                    finish();
                }
            }
        }.start();
    }

    //棧板更新
    private void palletListUp(String pId){

            url2=Constants.HTTP_LR_PALLETLISTUP + "?pId="+pId;

        Log.e("---------", "url2==fff===" + url2);
        showDialog();
        new Thread() {
            @Override
            public void run() {
                //把网络访问的代码放在这里
                String result = HttpUtils.queryStringForPost(url2);
                dismissDialog();
                Gson gson = new Gson();
                if (result != null) {
                    Log.e("---------", "result==fff===" + result);
                    JsonObject jsonObject = new JsonParser().parse(result).getAsJsonObject();
                    String errCode = jsonObject.get("errCode").getAsString();
                    lrInfoList = new ArrayList<LRMessage>();
                    if (errCode.equals("200")) {
                        JsonArray array = jsonObject.get("data").getAsJsonArray();


                        for (JsonElement type : array) {
                            LRMessage humi = gson.fromJson(type, LRMessage.class);
                            lrInfoList.add(humi);
                        }
                        Message message = new Message();
                        message.what = MESSAGE_SET_UP_LIST;
                        message.obj = jsonObject.get("errMessage").getAsString();
                        mHandler.sendMessage(message);

                    } else {
                        Log.e("-----------", "result==" + result);
                        Message message = new Message();
                        message.what = MESSAGE_TOAST;
                        message.obj = jsonObject.get("errMessage").getAsString();
                        mHandler.sendMessage(message);
                    }
                } else {
                    Message message = new Message();
                    message.what = MESSAGE_NETMISTAKE;
                    mHandler.sendMessage(message);
                    finish();
                }
            }
        }.start();
    }
    @SuppressLint("HandlerLeak")
    Handler mHandler = new Handler() {
        @SuppressLint("HandlerLeak")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MESSAGE_TOAST://Toast彈出
                    if (msg.obj.toString().equals("200")){

                        ToastUtils.showLong(LRPalletListActivity.this, "完成");
                        finish();
                    }else{
                        if (lrInfoList!=null){
                            lrInfoList.clear();
                        dnReformAdapter = new DNReformAdapter(LRPalletListActivity.this, lrInfoList,"QRP", "pallet");
                        lvNormal.setAdapter(dnReformAdapter);}
                        ToastUtils.showLong(LRPalletListActivity.this, msg.obj.toString());
                    }
                    break;
                case MESSAGE_NETMISTAKE://Toast彈出
                    ToastUtils.showLong(LRPalletListActivity.this, R.string.net_mistake);
                    break;
                case MESSAGE_SET_LIST://進度賦值

                   if (lrInfoList!=null){
                       lrInfoList.add(scanInfo.get(0));
                   }else{
                       lrInfoList=new ArrayList<>();
                       lrInfoList.add(scanInfo.get(0));
                   }

                   Log.e("----","scanInfo.get(0).getPALLETNO();"+scanInfo.get(0).getPALLETNO());
                   FoxContext.getInstance().setLrMessageList(lrInfoList);
                    dnReformAdapter = new DNReformAdapter(LRPalletListActivity.this, lrInfoList,"QRP", "pallet");
                    lvNormal.setAdapter(dnReformAdapter);
                    setListViewHeightBasedOnChildren(lvNormal);
                    break;
                case MESSAGE_SET_UP_LIST://更新棧板明細

                    FoxContext.getInstance().setLrMessageList(lrInfoList);
                    dnReformAdapter = new DNReformAdapter(LRPalletListActivity.this, lrInfoList, "QRP","pallet");
                    lvNormal.setAdapter(dnReformAdapter);
                    setListViewHeightBasedOnChildren(lvNormal);
                    break;
                case Constants.MESSAGE_ALERT://x卸貨成功
                    ToastUtils.showLong(LRPalletListActivity.this, msg.obj.toString());
                    finish();
                    break;
//                case MESSAGE_SET_ROOM://區域賦值
//                    setRoom();
//                    break;
            }
            super.handleMessage(msg);
        }
    };
    //更新指定單號狀態
    private void carStatusUp(String pId,String status,String creator){
        try {
            String status1 =  URLEncoder.encode(URLEncoder.encode(status, "UTF-8"), "UTF-8");
            String creator1 =  URLEncoder.encode(URLEncoder.encode(creator, "UTF-8"), "UTF-8");

            url2=Constants.HTTP_LR_CARSTATUSUP + "?pId="+pId+"&status="+status1+"&creator="+creator1;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        Log.e("---------", "url2==fff===" + url2);
        showDialog();
        new Thread() {
            @Override
            public void run() {
                //把网络访问的代码放在这里
                String result = HttpUtils.queryStringForPost(url2);
                dismissDialog();
                Gson gson = new Gson();
                if (result != null) {
                    Log.e("---------", "result==fff===" + result);
                    JsonObject jsonObject = new JsonParser().parse(result).getAsJsonObject();
                    String errCode = jsonObject.get("errCode").getAsString();
                    if (errCode.equals("200")) {

                        Message message = new Message();
                        message.what = MESSAGE_TOAST;
                        message.obj = jsonObject.get("errCode").getAsString();
                        mHandler.sendMessage(message);

                    } else {
                        Log.e("-----------", "result==" + result);
                        Message message = new Message();
                        message.what = MESSAGE_TOAST;
                        message.obj = jsonObject.get("errMessage").getAsString();
                        mHandler.sendMessage(message);
                    }
                } else {
                    Message message = new Message();
                    message.what = MESSAGE_NETMISTAKE;
                    mHandler.sendMessage(message);
                    finish();
                }
            }
        }.start();
    }
    private void aboutAlert(String msg, final int type) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("提示信息")
                .setMessage(msg)
                .setCancelable(false)
                .setNeutralButton("取消", new DialogInterface.OnClickListener(){
                    @Override
                    public void onClick(DialogInterface dialog, int id) {
                        // TODO Auto-generated method stub}
                    }  })
                .setPositiveButton("確認", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int id) {
                        // TODO Auto-generated method stub
                        if (type == MESSAGE_SET_STOP) {
                            carStatusUp(pId,"結束裝貨",FoxContext.getInstance().getName());

                        }else if (type == MESSAGE_ALERT){
                            planOver();
                        }
                    }
                });
        AlertDialog alert = builder.create();
        alert.show();
    }

    @Override
    protected void onStart() {
        super.onStart();
        lrInfoList=new ArrayList<>();
        lrInfoList.addAll(FoxContext.getInstance().getLrMessageList());
        if (qrResult.equals("")&&flag.equals("FH")){
            palletListUp(pId);
        }else if (!flag.equals("SH")){
            upScan(pId, qrResult);
        }
    }


}